<template>
  <div class="login-page">
    <el-card>
      <template #header>
        <div>黑马面经运营后台</div>
      </template>
      <!-- 表单校验四要素 -->
      <!-- el-from :rules :model -->
      <!-- el-form-item:  prop -->
      <!-- el-input  v-model -->
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item class="tc">
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'LoginIndex',
  data () {
    return {
      form: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        // [] 的意思是可以加多条校验规则
        // [] 中的 {} 的意思 就是校验规则
        // required: 必填
        // message: 错误发生时的提示文本,
        // trigger:触发条件 只有两个值 blur  change
        username: [
          { required: true, message: '用户名不可为空', trigger: ['blur', 'change'] },
          { min: 5, max: 11, message: '用户名的长度应该在5-11位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不可为空', trigger: 'blur' },
          // 5-10 正则校验
          { pattern: /^\w{5,10}$/, message: '密码的长度应该在5-10位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin () {
      // this.$refs['form']
      this.$refs.form.validate(async (flag) => {
        // flag 整个表单的校验结果
        // 都校验通过 falg :true
        // 只要有一个没校验通过： false
        if (!flag) return
        // const res = await loginApi(this.form)
        // // console.log(res.data.data.token)
        // this.$store.commit('user/setToken', res.data.data.token)
        await this.$store.dispatch('user/loginActions', this.form)
        this.$router.push('/')
      })
    },
    reset () {
      // resetFields 只能清空绑定了prop的表单域
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: center;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header {
      height: 80px;
      background: rgba(114, 124, 245, 1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
